package org.xbzheng.sc.core.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.xbzheng.sc.exception.CryptoException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @Created by Administrator on 2016/7/21.
 */
public class SecurityUtil {

    public static String md5(final String password){
        DigestUtils.sha256(password);
        return DigestUtils.md5Hex(password);
    }

    public static String aesEncrypt(final String data, final String encryptKey) throws CryptoException {
        String result = data;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(128, new SecureRandom(encryptKey.getBytes()));
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(generator.generateKey().getEncoded(), "AES"));
            result = Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            throw new CryptoException("AES encrypt fail:", e);
        }
        return result;
    }

    public static String aesDecrypt(final String encrypt, final String encryptKey) throws CryptoException {
        String result = encrypt;
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(128, new SecureRandom(encryptKey.getBytes()));

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(generator.generateKey().getEncoded(), "AES"));

            result = new String(cipher.doFinal(Base64.decodeBase64(encrypt)));
        } catch (Exception e) {
            throw new CryptoException("AES decrypt fail:", e);
        }
        return result;
    }

    public static void main(String[] args) throws CryptoException {
        System.out.println(SecurityUtil.md5("zheng"));
        System.out.println(aesEncrypt("user", "hun"));
        System.out.println(aesDecrypt("hiPAm8pjFOlc14xpjyR8jg==", "hun"));
    }
}
